<template>
  <div class="map-container">
    <div class="header-container">
      <div class="emergency-header">
        <div class="black-block"></div>
        <div class="red-title">
          <el-icon><MapLocation /></el-icon>
          失踪人员的地理分布
        </div>
      </div>
    </div>
    <a class="back-button"
       :style="{ display: backButtonVisible ? 'inline-block' : 'none' }"
       @click="goBack">
      返回上一级
    </a>
    <div id="map-chart"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import $ from 'jquery';
import missingPeopleCountData from '@/views/Home/HeatMapData.json';
import {MapLocation} from "@element-plus/icons-vue"; // 导入 JSON 数据

const myChart = ref<echarts.ECharts | null>(null);
const mapList = ref<any[]>([]);
const backButtonVisible = ref(false);
const globalMaxValue = ref(0); // 添加全局最大值变量

// 返回按钮事件
const goBack = () => {
  if (mapList.value.length >= 2) {
    const { name, adcode } = mapList.value[mapList.value.length - 2];
    mapList.value.splice(-2, 2);
    getJSON({ name, adcode }, (data) => {
      renderChart(name, data);
    });
  }
};

// 获取地图JSON数据
const getJSON = ({ name, adcode }: { name: string; adcode: number }, callback: (data: any) => void) => {
  const url = `/geo/${adcode}_full.json`;
  $.getJSON(url, (data) => {
    callback(data);
    setBackbtn({ name, adcode });
  }).fail((jqXHR, textStatus, errorThrown) => {
    console.error('Error fetching JSON:', textStatus, errorThrown);
  });
};

// 设置返回按钮状态
const setBackbtn = ({ name, adcode }: { name: string; adcode: number }) => {
  mapList.value.push({ name, adcode });
  backButtonVisible.value = adcode !== 100000;
};

// 初始化中国地图
const initChinaMap = () => {
  mapList.value = [];
  getJSON({ name: 'china', adcode: 100000 }, (data) => {
    renderChart('china', data);
  });
};

// 渲染地图
const renderChart = (name: string, data: any) => {
  echarts.registerMap(name, data);
  const mapdata = data.features.map((item: any) => {
    const adcode = item.properties.adcode;
    const found = missingPeopleCountData.find((item: any) => item.adcode === adcode);
    const count = found ? found.count : 0;
    return {
      ...item.properties,
      value: count
    };
  });
  
  // 只在初始化中国地图时更新全局最大值
  if (name === 'china' && globalMaxValue.value === 0) {
    globalMaxValue.value = Math.max(...mapdata.map((item: { value: number }) => item.value));
  }
  
  setOption(name, mapdata);
};

// 设置图表配置
const setOption = (name: string, data: any[]) => {
  const colorStops = [
    { offset: 0, color: '#fff1f0' },
    { offset: 0.2, color: '#ffccc7' },
    { offset: 0.5, color: '#ffa39e' },
    { offset: 0.7, color: '#ff7875' },
    { offset: 1, color: '#fb4c49' },
  ];

  // 判断是否为小屏幕
  const isSmallScreen = window.innerWidth <= 1280;

  const option: echarts.EChartsOption = {
    tooltip: {
      formatter: (params: any) => {
        if (params?.data) {
          const { adcode, name, level, value } = params.data;
          return `地区: ${name}<br>失踪人口数量: ${value === 0 ? '-' : value}`;
        }
        return '';
      },
    },
    geo: [{
      map: name,
      roam: false,
      label: {
        show: true,
        color: '#666',
        fontSize: isSmallScreen ? 6 : 8,
      },
      itemStyle: {
        areaColor: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: colorStops,
          global: false
        },
        borderColor: 'rgba(0, 0, 0, 0.2)',
      },
      emphasis: {
        itemStyle: {
          areaColor: '#b62b01',
          borderColor: '#f29100'
        },
        label: {
          fontSize: isSmallScreen ? 12 : 16,
          color: '#f29100'
        }
      },
      top: isSmallScreen ? '0%' : '-5%',
      bottom: isSmallScreen ? '0%' : (name === 'china' ? '-45%' : '0%'),
      left: isSmallScreen ? '0%' : '0%',
      right: isSmallScreen ? '0%' : '0%',
      aspectScale: 0.75,
      layoutCenter: ['50%', '45%'],
      layoutSize: '105%',
      zoom: name === 'china' ? 1.3 : 1,
      center: name === 'china' ? [105, 38] : undefined,
      scaleLimit: {
        min: 1,
        max: name === 'china' ? 1.3 : 1.5
      },
      regions: isSmallScreen ? [{
        name: '南海诸岛',
        itemStyle: {
          areaColor: 'transparent',
          borderColor: 'transparent'
        },
        label: {
          show: false
        }
      }] : undefined
    }],
    visualMap: {
      type: 'continuous',
      min: 0,
      max: globalMaxValue.value,
      text: ['失踪人口多', '失踪人口少'],
      realtime: false,
      calculable: true,
      inRange: {
        color: colorStops.map(stop => stop.color)
      },
      left: '2%',
      bottom: '2%',
      itemWidth: isSmallScreen ? 12 : 20,
      itemHeight: isSmallScreen ? 60 : 120,
      textStyle: {
        fontSize: isSmallScreen ? 8 : 12
      },
      orient: 'vertical'
    },
    series: [{
      type: 'map',
      map: name,
      geoIndex: 0,
      data: data.map(item => ({
        ...item,
        value: item.value === 0 || item.value === null ? 0 : item.value
      }))
    }]
  };
  myChart.value?.setOption(option, true);
};

// 响应式调整
const handleResize = () => {
  if (myChart.value) {
    // 先销毁当前实例
    myChart.value.dispose();
    // 重新初始化图表
    const chartDom = document.getElementById('map-chart')!;
    myChart.value = echarts.init(chartDom);
    
    // 重新渲染当前地图
    const name = mapList.value[mapList.value.length - 1]?.name || 'china';
    if (name === 'china') {
      initChinaMap();
    } else {
      const currentMap = mapList.value[mapList.value.length - 1];
      if (currentMap) {
        getJSON({ name: currentMap.name, adcode: currentMap.adcode }, (data) => {
          renderChart(currentMap.name, data);
        });
      }
    }
  }
};

// 添加屏幕尺寸检测
const isSmallScreen = ref(false);

const checkScreenSize = () => {
  isSmallScreen.value = window.innerWidth <= 1280;
};

onMounted(() => {
  const chartDom = document.getElementById('map-chart')!;
  myChart.value = echarts.init(chartDom);

  // 初始化屏幕尺寸检测
  checkScreenSize();
  
  // 事件监听
  window.addEventListener('resize', handleResize);
  window.addEventListener('resize', checkScreenSize);
  
  myChart.value.on('click', (params: any) => {
    if (params.data) {
      const { adcode, name, level } = params.data;
      if (level === 'district') {
        initChinaMap();
        return;
      }
      getJSON({ name, adcode }, (data) => renderChart(name, data));
    }
  });

  initChinaMap();
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('resize', checkScreenSize);
  myChart.value?.dispose();
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 10px;
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

#map-chart {
  width: 100%;
  height: calc(100% - 50px);
  min-height: 300px;
  position: relative;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
}

.emergency-header {
  display: flex;
  height: 50px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.black-block {
  width: 10px;
  background: var(--reverse-background-color);
}

.red-title {
  flex: 1;
  background: #f45c5c;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-size: 22px;
  font-weight: 600;
  gap: 10px;
}

.back-button {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 1000;
  padding: 8px 15px;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  transition: all 0.2s;
}

.back-button:hover {
  background: #f5f5f5;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

/* 小屏幕适配 */
@media (max-width: 1280px) {
  .map-container {
    min-height: 40vh;
    padding: 0;
    width: 100%;
    height: 100%;
    aspect-ratio: 16/9;
  }

  #map-chart {
    min-height: 200px;
    height: 100%;
    width: 100%;
  }

  .header-container {
    display: none; /* 隐藏标题部分 */
  }

  .back-button {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    padding: 4px 10px;
    font-size: 12px;
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  }
}
</style>
